package com.yanglun.mvp;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import com.yanglun.mvp.db.DatabaseHelper;
import com.yanglun.mvp.db.UserDBModel;

public class MVCActivity extends AppCompatActivity implements View.OnClickListener {
    private EditText id, first, last;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mvc);
        findViewById(R.id.save).setOnClickListener(this);
        findViewById(R.id.load).setOnClickListener(this);
        id = (EditText) findViewById(R.id.id);
        first = (EditText) findViewById(R.id.first);
        last = (EditText) findViewById(R.id.last);

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.save: {
                try {
                    DatabaseHelper dbHelper = DatabaseHelper.getHelper(this);
                    UserDBModel dbModel = new UserDBModel();
                    dbModel.setFirstname(first.getText().toString());
                    dbModel.setLastname(last.getText().toString());
                    dbModel.setId(Integer.valueOf(id.getText().toString()).intValue());
                    dbHelper.getUserDao().createOrUpdate(dbModel);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            break;
            case R.id.load:
                try {
                    DatabaseHelper dbHelper = DatabaseHelper.getHelper(this);
                    UserDBModel userdbModel = dbHelper.getUserDao().queryForId(Integer.valueOf( id.getText().toString()).intValue());
                    first.setText(userdbModel.getFirstname());
                    last.setText(userdbModel.getLastname());
                    id.setText(String.valueOf(userdbModel.getId()));
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            default:
                break;
        }
    }
}

